<?php
/**
 * Created by PhpStorm.
 * User: zskj
 * Date: 2019/2/25
 * Time: 16:06
 */

namespace app\tools;

class Sms{

    public $key = '0dba4d5aaff44e48d126dc8ea8031f2d';
    public $tpl_id = '137638';

    function __construct($tpl_id = 0)
    {
        if($tpl_id) $this->tpl_id = $tpl_id;
    }

    function send($mobile, $value){

        $redis = RedisCache::getInstance();
        $key = 'sms_'.$mobile;
        $key1 = 'sms_p_'.$mobile;

        $flag = $redis->get($key1);

        if(!$flag){
            $tpl_value = urlencode('#code#='.$value);
            $url = 'http://v.juhe.cn/sms/send?mobile='.$mobile.'&tpl_id='.$this->tpl_id.'&tpl_value='.$tpl_value.'&key='.$this->key;
            $data = curl($url);

            $data = json_decode($data, true);
//            dump($data);
            if($data['error_code'] == 0){

                $redis->setex($key, 300, $value);
                $redis->setex($key1, 60, 1);

            }else{
                exit(fail("SEND_LIMITED_ERROR"));
            }

        }else{
            exit(fail("SEND_OFTEN"));
        }

    }

    static function checkSms($mobile, $value){

        $redis = RedisCache::getInstance();
        $key = 'sms_'.$mobile;
        $code = $redis->get($key);

        if($code){
            if($code != $value){
                exit(fail("SMS_CODE_ERROR"));
            }
            $redis->delete($key);

        }else{
            exit(fail("SMS_CODE_OVERDUE"));
        }

        return true;
    }

}